Imports System
Imports System.DateTime
Imports DotNetNuke.Services.Mail
Imports DotNetNuke.Entities.Portals

Namespace RTP.HTMLNewsletter

#Region "NewsletterSchedule Class "

    Public Class NewsletterSchedule
        Inherits DotNetNuke.Services.Scheduling.SchedulerClient

#Region "Private Members"

#End Region

#Region "Constructors"
        Public Sub New(ByVal objScheduleHistoryItem As DotNetNuke.Services.Scheduling.ScheduleHistoryItem)
            MyBase.new()
            Me.ScheduleHistoryItem = objScheduleHistoryItem
        End Sub
#End Region

#Region "Methods"
        Public Overrides Sub DoWork()
            Try
                Dim returnstr As String = "Newsletter Schedule completed successfully - Nothing to do."
                Dim objNewsletterCtl As New NewsletterController
                Dim objNewsletter As New NewsletterInfo
                Dim objNewsletterUserCtl As New NewsletterUserController
                Dim arrNewsletterUsers As ArrayList = objNewsletterUserCtl.GetNewsletterUserUnsent()
                Dim prvNLID As Integer = 0
                Dim portalSettings As PortalSettings = Nothing
                For Each objNewsletterUser As NewsletterUserInfo In arrNewsletterUsers
                    If Not objNewsletterUser.Ignore Then
                        If prvNLID <> objNewsletterUser.NewsletterID Then
                            objNewsletter = objNewsletterCtl.GetNewsletterbyID(objNewsletterUser.NewsletterID)
                            portalSettings = CreatePortalSettings(objNewsletterUser.PortalAliasID)

                        End If
                        If objNewsletter.NewsletterBody = "" Then objNewsletter.NewsletterBody = " "
                        Send(objNewsletter.NewsletterUserID, objNewsletter.NewsletterEmail, objNewsletterUser.UserEmail, objNewsletter.NewsletterDesc, objNewsletter.NewsletterBody, objNewsletterUser.PortalAliasID, objNewsletter.ModuleID, objNewsletterUser.UserID, portalSettings)
                    End If
                    objNewsletterUserCtl.UpdateNewsletterUser(objNewsletterUser.NewsletterID, objNewsletterUser.UserID, objNewsletterUser.Ignore, True, objNewsletterUser.PublishDate)
                    returnstr = "Newsletter Schedule completed successfully - " + CStr(arrNewsletterUsers.Count) + " emails processed."
                Next
                Me.ScheduleHistoryItem.AddLogNote(returnStr)

                Me.ScheduleHistoryItem.Succeeded = True     'REQUIRED


            Catch exc As Exception      'REQUIRED
                Me.ScheduleHistoryItem.Succeeded = False    'REQUIRED
                Me.ScheduleHistoryItem.AddLogNote("HTML Newsletter Schedule failed - " + exc.ToString + " - " + Me.Status)    'OPTIONAL
                'notification that we have errored
                Me.Errored(exc)         'REQUIRED
                'log the exception
                LogException(exc)       'OPTIONAL
            End Try
        End Sub

        Private Sub Send(ByVal iFromID As Integer, ByVal strFrom As String, ByVal strTo As String, ByVal strSubject As String, ByVal strBody As String, ByVal PortalAliasID As Integer, ByVal ModuleID As Integer, ByVal iToID As Integer, ByVal portalSettings As PortalSettings)

            ' Use this for Messaging Controller
            ' Dim objMessage As New Message

            Dim mailFrom, mailTo, mailSubject, mailBody, mailBcc, mailBodyType As String

            If strBody.ToLower.Contains("[user:") Or strBody.ToLower.Contains("[profile:") Then
                Dim userCtl As New DotNetNuke.Entities.Users.UserController
                Dim userInfo As DotNetNuke.Entities.Users.UserInfo = userCtl.GetUser(portalSettings.PortalId, iToID)
                Dim locale As String = ""
                If Not userInfo.Profile.PreferredLocale Is Nothing Then
                    locale = userInfo.Profile.PreferredLocale
                Else
                    locale = portalSettings.DefaultLanguage
                End If
                If Not System.Web.HttpContext.Current.Items("UserInfo") Is Nothing Then
                    System.Web.HttpContext.Current.Items.Remove("UserInfo")
                End If
                System.Web.HttpContext.Current.Items.Add("UserInfo", userInfo)
                Dim trn As New Services.Tokens.TokenReplace(Services.Tokens.Scope.DefaultSettings, locale, portalSettings, userInfo, ModuleID)
                strBody = trn.ReplaceEnvironmentTokens(strBody)
            End If

            ''''''''''''''''''''''''''''''''''''''
            ' TODO - When DNN supports specific email address through Messaging Controller
            ' then this code can be converted/completed.
            ''''''''''''''''''''''''''''''''''''''
            'objMessage.ToUserID = iUserID
            'objMessage.Subject = strSubject
            'objMessage.Body = strBody
            'objMessage.Status = MessageStatusType.Unread
            'Dim objMessageController As New MessagingController
            'objMessageController.SaveMessage(objMessage)


            mailTo = strTo
            mailFrom = strFrom
            mailBcc = ""
            mailSubject = AddHref(strSubject, PortalAliasID)
            mailBody = AddHref(strBody, PortalAliasID)
            mailBodyType = "HTML"

            Mail.SendMail(mailFrom, mailTo, mailBcc, mailSubject, mailBody, "", mailBodyType, "", "", "", "")
        End Sub

        Private Function AddHref(ByVal Content As String, ByVal PortalAliasID As Integer) As String
            Dim domainurl As String = ""
            Dim objPortalAliases As PortalAliasController = New PortalAliasController
            Dim objPortalAlias As PortalAliasInfo

            objPortalAlias = objPortalAliases.GetPortalAliasByPortalAliasID(PortalAliasID)
            If Not objPortalAlias Is Nothing Then
                domainurl = objPortalAlias.HTTPAlias()
            End If
            If domainurl.IndexOf("/") > 0 Then
                domainurl = domainurl.Substring(0, domainurl.IndexOf("/"))
            End If

            Dim txtContent As String = Content
            If domainurl <> "" Then
                txtContent = Replace(txtContent, "src=""/", "src=""http://" & domainurl & "/")
                txtContent = Replace(txtContent, "href=""/", "href=""http://" & domainurl & "/")
            End If
            Return txtContent
        End Function


        Public Function CreatePortalSettings(ByVal PortalAliasID As Integer) As PortalSettings
            Dim CacheKey As String = "EventsPortalSettings" & PortalAliasID.ToString
            Dim ps As New PortalSettings
            Dim pscache As PortalSettings = CType(DotNetNuke.Common.Utilities.DataCache.GetCache(CacheKey), PortalSettings)

            If pscache Is Nothing Then
                ' Setup PortalSettings
                Dim objPortalAliases As PortalAliasController = New PortalAliasController
                Dim objPortalAlias As PortalAliasInfo

                objPortalAlias = objPortalAliases.GetPortalAliasByPortalAliasID(PortalAliasID)
                If objPortalAlias Is Nothing Then
                    Return Nothing
                End If
                Dim portalController As New PortalController
                Dim portal As Entities.Portals.PortalInfo = portalController.GetPortal(objPortalAlias.PortalID)


                With ps
                    .PortalAlias = objPortalAlias
                    .PortalId = portal.PortalID
                    .PortalName = portal.PortalName
                    .LogoFile = portal.LogoFile
                    .FooterText = portal.FooterText
                    .ExpiryDate = portal.ExpiryDate
                    .UserRegistration = portal.UserRegistration
                    .BannerAdvertising = portal.BannerAdvertising
                    .Currency = portal.Currency
                    .AdministratorId = portal.AdministratorId
                    .Email = portal.Email
                    .HostFee = portal.HostFee
                    .HostSpace = portal.HostSpace
                    .PageQuota = portal.PageQuota
                    .UserQuota = portal.UserQuota
                    .AdministratorRoleId = portal.AdministratorRoleId
                    .AdministratorRoleName = portal.AdministratorRoleName
                    .RegisteredRoleId = portal.RegisteredRoleId
                    .RegisteredRoleName = portal.RegisteredRoleName
                    .Description = portal.Description
                    .KeyWords = portal.KeyWords
                    .BackgroundFile = portal.BackgroundFile
                    .GUID = portal.GUID
                    .SiteLogHistory = portal.SiteLogHistory
                    .AdminTabId = portal.AdminTabId
                    .SuperTabId = portal.SuperTabId
                    .SplashTabId = portal.SuperTabId
                    .HomeTabId = portal.HomeTabId
                    .LoginTabId = portal.LoginTabId
                    .UserTabId = portal.UserTabId
                    .DefaultLanguage = portal.DefaultLanguage
                    .Pages = portal.Pages
                    .Users = portal.Users
                    If .HostSpace = Nothing Then
                        .HostSpace = 0
                    End If
                    If .DefaultLanguage Is Nothing Then
                        .DefaultLanguage = DotNetNuke.Services.Localization.Localization.SystemLocale
                    End If
                    If .TimeZone Is Nothing Then
                        .TimeZone = System.TimeZoneInfo.FindSystemTimeZoneById(DotNetNuke.Services.Localization.Localization.SystemTimeZone)
                    End If
                    .HomeDirectory = DotNetNuke.Common.Globals.ApplicationPath + "/" + portal.HomeDirectory + "/"
                End With
                DotNetNuke.Common.Utilities.DataCache.SetCache(CacheKey, ps)
            Else
                ps = pscache
            End If

            Try
                ' Now to put it into the HTTPContext
                If System.Web.HttpContext.Current Is Nothing Then
                    Dim page As String = ps.PortalAlias.HTTPAlias
                    Dim query As String = String.Empty
                    Dim output As System.IO.TextWriter = Nothing
                    Dim workerrequest As System.Web.Hosting.SimpleWorkerRequest = New System.Web.Hosting.SimpleWorkerRequest(page, query, output)
                    System.Web.HttpContext.Current = New System.Web.HttpContext(workerrequest)
                    System.Web.HttpContext.Current.Items.Add("PortalSettings", ps)
                Else
                    System.Web.HttpContext.Current.Items.Remove("PortalSettings")
                    System.Web.HttpContext.Current.Items.Add("PortalSettings", ps)
                End If
            Catch exc As Exception
            End Try

            Return ps
        End Function


#End Region



    End Class
#End Region
End Namespace